package com.xci.core.internal;

import com.xci.core.annotation.Authorize;
import com.xci.core.base.RestMessage;
import com.xci.core.helper.Helper;
import com.xci.core.helper.WebHelper;
import com.xci.sys.service.ModuleService;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

@Component
public class WebInterceptor implements HandlerInterceptor {
    /**
     * 在请求处理之前进行调用（Controller方法调用之前）
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 如果不是映射到方法直接放行
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        Method method = ((HandlerMethod) handler).getMethod();
        // 类/方法上有@AllowAnonymous,允许匿名登录,直接放行
        if (Helper.IsAllowAnonymous(method)) {
            return true;
        }

        String contextPath = request.getContextPath();
        boolean isAjaxRequest = WebHelper.isAjax(request);
        boolean isLogin = Sys.me().checkAndAutoLogin(request);
        //登录超时
        if (!isLogin) {
            if (isAjaxRequest) {//ajax请求
                WebHelper.writeJson(RestMessage.fail(Sys.setting().getWeb().getLoginTimeoutMessage()));
            } else {            //普通web请求
                response.sendRedirect(contextPath + Sys.setting().getWeb().getLoginUrl());
            }
            return false;
        }

        var currentUser = Sys.me().getCurrentUser();
        Authorize classAuth = method.getDeclaringClass().getAnnotation(Authorize.class);
        Authorize methodAuth = method.getAnnotation(Authorize.class);
        String codes = Const.EMPTY;
        if (methodAuth != null && Helper.isNotBlank(methodAuth.code())) {
            codes = methodAuth.code();
        } else if (classAuth != null && Helper.isNotBlank(classAuth.code())) {
            codes = classAuth.code();
        }
        if (Helper.isBlank(codes)){
            return true;
        }
        if (!Sys.me().isAuthorize(currentUser, codes)) {
            if (isAjaxRequest) {//ajax请求
                WebHelper.writeJson(RestMessage.fail(Sys.setting().getWeb().getUnAuthorizedMessage()));
            } else {            //普通web请求
                response.sendRedirect(contextPath + Sys.setting().getWeb().getUnAuthorizedUrl());
            }
            return false;
        }
        return true;
    }

// /**
//  * 请求处理之后进行调用，但是在视图被渲染之前（Controller方法调用之后）
//  */
// @Override
// public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
// }
//
// /**
//  * 在整个请求结束之后被调用，也就是在DispatcherServlet 渲染了对应的视图之后执行（主要是用于进行资源清理工作）
//  */
// @Override
// public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
// }
}
